package cn.net.cfss.fgbp.face.console.controller;

import cn.net.cfss.fgbp.api.console.dto.SysRoleDto;
import cn.net.cfss.fgbp.api.console.dto.SysUserRoleDto;
import cn.net.cfss.fgbp.api.console.inte.ISysRoleProjectService;
import cn.net.cfss.fgbp.api.console.inte.ISysRoleService;
import cn.net.cfss.fgbp.api.console.inte.ISysUserService;
import cn.net.cfss.fgbp.api.console.vo.SysRoleVo;
import cn.net.cfss.fgbp.base.common.GlobalConstants;
import cn.net.cfss.fgbp.base.constant.ErrCodeEnum;
import cn.net.cfss.fgbp.base.controller.BaseController;
import cn.net.cfss.fgbp.base.page.PageData;
import cn.net.cfss.fgbp.face.console.util.HttpClientUtil;
import cn.net.cfss.fgbp.face.console.util.ReturnUtil;
import cn.net.cfss.fgbp.face.console.vo.BaseParas;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * @author oygq
 * @title: SysRoleController
 * @description: 角色
 * @date 2019/4/3 14:53
 */

@RestController
@Slf4j
@RequestMapping("console/role")
public class SysRoleController extends BaseController {

    @Autowired
    ISysRoleService roleService;

    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysRoleProjectService roleProjectService;
    /**
     * 服务商级别管理员
     */
    @Value("${application.resource.servProAdmin}")
    private String servProAdmin;
    /**
     * 超级管理员
     */
    @Value("${application.resource.superAdmin}")
    private String superAdmin;
    /**
     * 超级管理员
     */
    @Value("${crm.getProject}")
    private String getProjectUrl;

    @ApiOperation("角色新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String insert(@RequestBody BaseParas paras) {
        SysRoleVo vo = JSONObject.toJavaObject(paras.getPlain(), SysRoleVo.class);
        if (null == vo) {
            return ReturnUtil.returnErr(ErrCodeEnum.ERR_VAII);
        }
        vo.setCreateBy(Long.parseLong(request.getHeader(GlobalConstants.HEADER_USERID)));
        //查询角色是否存在
        if (!roleService.uniquenessCheck(vo.getRoleCode(), vo.getId())) {
            return ReturnUtil.returnErr("角色编码或角色名称已存在");
        }

        if (roleService.insert(vo)) {
            return ReturnUtil.returnSucc();
        }
        return ReturnUtil.returnErr(ErrCodeEnum.ERR);
    }

    @ApiOperation("角色修改")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String update(@RequestBody BaseParas paras) {
        SysRoleVo vo = JSONObject.toJavaObject(paras.getPlain(), SysRoleVo.class);
        if (null == vo) {
            return ReturnUtil.returnErr(ErrCodeEnum.ERR_VAII);
        }
        vo.setUpdateBy(Long.parseLong(request.getHeader(GlobalConstants.HEADER_USERID)));
        //查询角色是否存在
        if (!roleService.uniquenessCheck(vo.getRoleCode(), vo.getRoleId())) {
            return ReturnUtil.returnErr("角色编码或角色名称已存在");
        }
        vo.setId(Long.valueOf(vo.getRoleId()));
        if (roleService.update(vo)) {
            return ReturnUtil.returnSucc();
        }
        return ReturnUtil.returnErr(ErrCodeEnum.ERR);
    }

    @ApiOperation("角色删除")
    @RequestMapping(value = "/delete/{roleId}", method = RequestMethod.POST)
    public String delete(@PathVariable Long roleId) {
        if (roleId == null) {
            return ReturnUtil.returnErr(ErrCodeEnum.ERR_VAII);
        }
        if (!this.bindingUser(roleId)) {
            return ReturnUtil.returnErr("角色已绑定用户");
        }
        if (roleService.delete(roleId)) {
            return ReturnUtil.returnSucc();
        }
        return ReturnUtil.returnErr(ErrCodeEnum.ERR);
    }

    @ApiOperation("角色批量删除")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(@RequestBody BaseParas paras) {
        //List<Long> orgIds = (List<Long>) paras.getPlain().get("roleIds");
        JSONArray jsonArray = paras.getPlain().getJSONArray("roleIds");
        List<Long> orgIds = JSONObject.parseArray(jsonArray.toJSONString(), Long.class);
        if (null == orgIds || orgIds.size() == 0) {
            return ReturnUtil.returnErr(ErrCodeEnum.ERR_VAII);
        }

        if (!this.bindingUser(orgIds)) {
            return ReturnUtil.returnErr("角色已绑定用户");
        }
        if (roleService.deleteBatch(orgIds)) {
            return ReturnUtil.returnSucc();
        }
        return ReturnUtil.returnErr(ErrCodeEnum.ERR);
    }

    @ApiOperation("角色查询")
    @RequestMapping(value = "/query/{roleId}", method = RequestMethod.POST)
    public String query(@PathVariable Long roleId) {
        if (null == roleId) {
            return ReturnUtil.returnErr(ErrCodeEnum.ERR_VAII);
        }
        SysRoleVo role = roleService.queryById(roleId);
        return ReturnUtil.returnSucc(role);
    }

    @ApiOperation("角色查询List")
    @RequestMapping(value = "/query/list", method = RequestMethod.POST)
    public String queryList(@RequestBody BaseParas paras) {
        SysRoleVo search = JSONObject.toJavaObject(paras.getPlain().getJSONObject("search"), SysRoleVo.class);
        PageData<SysRoleDto> role = PageData.createPagerData(paras.getPlain().getIntValue("pageSize"),
                paras.getPlain().getIntValue("pageNum"), search);
        role = roleService.queryList(role);
        return ReturnUtil.returnSucc(role, role.getRows());
    }

    @ApiOperation("角色的唯一性校验")
    @RequestMapping(value = "/uniquenessCheck", method = RequestMethod.POST)
    public String uniquenessCheck(@RequestBody BaseParas paras) {
        try {
            String roleCode = paras.getPlain().getString("code");
            Long id = paras.getPlain().getLong("id");
            return ReturnUtil.returnSucc(roleService.uniquenessCheck(roleCode, id));
        } catch (Exception e) {
            log.error("角色的唯一性校验请求失败！", e.getMessage());
            return ReturnUtil.returnErr("角色的唯一性校验请求失败！");
        }
    }

    /**
     * 判断角色是否绑定用户
     *
     * @return
     */
    private Boolean bindingUser(List<Long> ids) {
        for (Long id : ids) {
            SysUserRoleDto dto = new SysUserRoleDto();
            dto.setRoleId(id);
            List<SysUserRoleDto> userRoleDtos = sysUserService.queryUserRole(dto);
            if (userRoleDtos.size() > 0) {
                return false;
            }
        }
        return true;
    }

    private Boolean bindingUser(Long id) {
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        return bindingUser(ids);
    }


    @ApiOperation("角色绑定项目列表选项")
    @RequestMapping(value = "/queryAllProject", method = RequestMethod.POST)
    public String queryAllProject(@RequestBody BaseParas paras) {
        Long userId = getUserId();

        try {
            if (userId == null) {
                return ReturnUtil.returnErr("无法获取到当前登录人！");
            }
            //超级管理员查询所有项目
            if (sysUserService.checkUserRole(superAdmin, userId)) {
                String rest = HttpClientUtil.executPost(getProjectUrl, JSONObject.toJSONString(paras), "UTF-8", ContentType.APPLICATION_JSON);
                return rest;
                //服务商级别的查询改服务商绑定的所有项目
            } else if (sysUserService.checkUserRole(servProAdmin, userId)) {
                Long userSpId = getUserSpId();
                JSONObject jsonObject = paras.getPlain();
                JSONObject json = jsonObject.getJSONObject("search");
                json.put("spId", userSpId);
                String rest = HttpClientUtil.executPost(getProjectUrl, JSONObject.toJSONString(paras), "UTF-8", ContentType.APPLICATION_JSON);
                return rest;
                //其他的只能查看到自己绑定的项目
            } else {
                SysUserRoleDto userRoleDto = new SysUserRoleDto();
                userRoleDto.setUserId(userId);
                List<SysUserRoleDto> userRoleDtos = sysUserService.queryUserRole(userRoleDto);
                List<Long> roleIds = new ArrayList<Long>();
                if (userRoleDtos != null) {
                    for (SysUserRoleDto userRole : userRoleDtos) {
                        roleIds.add(userRole.getRoleId());
                    }
                }
                List<String> projectIds = roleProjectService.queryByProjectId(roleIds);
                JSONObject jsonObject = paras.getPlain();
                JSONObject json = jsonObject.getJSONObject("search");
                json.put("ids", projectIds);
                String rest = HttpClientUtil.executPost(getProjectUrl, JSONObject.toJSONString(paras), "UTF-8", ContentType.APPLICATION_JSON);
                return rest;
            }
        } catch (Exception e) {
            log.error("角色绑定项目列表选项:{}", e.getMessage());
        }

        return ReturnUtil.returnErr(ErrCodeEnum.ERR);
    }

    private String getJsonString(List<String> ids) {
        JSONObject json = new JSONObject();

        JSONObject plain = new JSONObject();
        plain.put("pageSize", 0);
        plain.put("pageNum", 0);

        JSONObject search = new JSONObject();
        search.put("ids", ids);

        plain.put("search", search);
        json.put("plain", plain);
        return json.toJSONString();
    }
}


